package gov.jyy.operationlog.core;

import java.util.concurrent.*;


public class LogSendExecutor {


    /**
     * 有效核心处理器
     */
    private static final int AVALIABLE_PROCESSORS = Runtime.getRuntime().availableProcessors();
    /**
     * 核心线程数
     */
    private static final int CORE_POOL_SIZE = Math.max((AVALIABLE_PROCESSORS / 2), 1);
    /**
     * 最大线程数
     */
    private static final int MAX_IMUM_POOL_SIZE = AVALIABLE_PROCESSORS;
    /**
     * 线程保存时间
     */
    private static final long KEEP_LIVE_TIME = 1L;

    /**
     * 核心线程数及队列满了，就会新建线程
     */
    private static final BlockingQueue<Runnable> WORK_QUEUE = new ArrayBlockingQueue<>(30);

    /**
     * 线程工程，可以指定线程名字以区分业务
     */
    private static final ThreadFactory THREAD_FACTORY = new TaskThreadFactory();

    /**
     * 策略
     */
    private static final RejectedExecutionHandler HANDLER = new ThreadPoolExecutor.CallerRunsPolicy();

    /**
     * RejectedExecutionHandler handler;
     * 1.抛出异常（默认）AbortPolicy
     * 2.无声地放弃当前任务。DiscardPolicy
     * 3.丢弃队列最靠前的任务。DiscardOldestPolicy
     * 4.用调用者所在的线程来执行任务（除非线程池关闭）CallerRunsPolicy
     */
    public static final ExecutorService EXECUTOR = new ThreadPoolExecutor(CORE_POOL_SIZE, MAX_IMUM_POOL_SIZE
            , KEEP_LIVE_TIME, TimeUnit.MINUTES, WORK_QUEUE, THREAD_FACTORY, HANDLER);


    private static class TaskThreadFactory implements ThreadFactory {
        private static final ThreadFactory defaultFactory = Executors.defaultThreadFactory();

        @Override
        public Thread newThread(Runnable r) {
            Thread t = defaultFactory.newThread(r);
            t.setName("log-save-thread");
            return t;
        }
    }
}
